package gui;
/**
 * Responsible for drawing all the UI elements for the Settings menu
 */
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;

import controller.SettingsController;

public class SettingsDisplay extends Display {
	private SettingsController settingsController;
	
	private JTextField textFieldNewUsername;
	private JPasswordField oldPasswordField;
	private JPasswordField newPasswordField;
	private JPasswordField retypeNewPasswordField;
	private JTextField firstNameField;
	private JTextField lastNameField;
	private JTextField ageField;
	private JComboBox genderField;
	private JTextField locationField;
	
	/**
	 * Creates a new SettingsDisplay class and links it to a SettingsController
	 * @param c Controller to be linked
	 */
	public SettingsDisplay(SettingsController c) {
		super();
		drawSettings();
		this.settingsController = c;
	}
	
	/**
	 * Creates a new SettingsDisplay class and links it to a SettingsController
	 * and Display
	 * @param c Controller to be linked
	 * @param lastDisplay Display to be linked
	 */
	public SettingsDisplay(SettingsController c, Display lastDisplay) {
		super(lastDisplay.getFrame());
		this.settingsController = c;
		drawSettings();
	}

	/**
	 * Draws all the UI elements associated with the Settings menu
	 */
	private void drawSettings() {
		frame.getContentPane().removeAll();		
		
		ImagePanel SETTINGS = new ImagePanel(new ImageIcon(GUI.class.getResource("/images/Menu_BG_V3.png")).getImage());
		SETTINGS.setBackground(Color.BLACK);
		frame.getContentPane().add(SETTINGS, "name_774204026396720");
		SETTINGS.setLayout(null);
		
		
		JLabel lblSettingsTitle = new JLabel("");
		lblSettingsTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblSettingsTitle.setBounds(0, 15, 660, 105);
		lblSettingsTitle.setIcon(new ImageIcon(GUI.class.getResource("/images/settings_title.png")));
		SETTINGS.add(lblSettingsTitle);
		
		
		final JPanel INFO = new JPanel();
		INFO.setBackground(new Color(16,28,9));
		INFO.setBounds(197, 226, 265, 213);
		INFO.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
		INFO.setVisible(false);
		SETTINGS.add(INFO);
		INFO.setLayout(null);
		
		final JPanel PASSWORD = new JPanel();
		PASSWORD.setBackground(new Color(16,28,9));
		PASSWORD.setBounds(197, 226, 265, 157);
		PASSWORD.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
		PASSWORD.setVisible(false);
		
		final JPanel USERNAME = new JPanel();
		USERNAME.setBackground(new Color(16,28,9));
		USERNAME.setBounds(197, 226, 265, 116);
		USERNAME.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
		USERNAME.setVisible(false);
		SETTINGS.add(USERNAME);
		USERNAME.setLayout(null);
		
		JLabel lblCurrentUsernameText = new JLabel("Current Username:");
		lblCurrentUsernameText.setBounds(6, 15, 115, 16);
		lblCurrentUsernameText.setForeground(Color.WHITE);
		USERNAME.add(lblCurrentUsernameText);
		
		final JLabel lblCurrentUsername = new JLabel(settingsController.getUser().getUsername());
		lblCurrentUsername.setBounds(125, 15, 115, 16);
		lblCurrentUsername.setForeground(Color.WHITE);
		USERNAME.add(lblCurrentUsername);
		
		
		JLabel lblNewUsername = new JLabel("New Username:");
		lblNewUsername.setHorizontalAlignment(SwingConstants.LEFT);
		lblNewUsername.setForeground(Color.WHITE);
		lblNewUsername.setBounds(6, 49, 106, 16);
		USERNAME.add(lblNewUsername);
				
		textFieldNewUsername = new JTextField();
		textFieldNewUsername.setBounds(124, 43, 135, 28);
		USERNAME.add(textFieldNewUsername);
		textFieldNewUsername.setColumns(10);
		
		JButton btnConfirm = new JButton("Confirm");
		btnConfirm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				INFO.setVisible(false);
				PASSWORD.setVisible(false);
				USERNAME.setVisible(false);
				
				boolean goodUsernameChange = true;
				
				if (textFieldNewUsername.getText().length() < 4 || textFieldNewUsername.getText().length() > 15) {
					goodUsernameChange = false;
				}
				
				String temp = textFieldNewUsername.getText();
				for (int i = 0; i < temp.length(); i++) {
					if (!('0' <= temp.charAt(i) && temp.charAt(i) <= '9' || 'a' <= temp.charAt(i) && temp.charAt(i) <= 'z' || 'A' <= temp.charAt(i) && temp.charAt(i) <= 'Z' || temp.charAt(i) == '.' || temp.charAt(i) == '_')) {
						goodUsernameChange = false;
					}
				}
				
				if (goodUsernameChange) {
					try {
						if (settingsController.setNewUsername(textFieldNewUsername.getText())) {
							lblCurrentUsername.setText(settingsController.getUser().getUsername());
							JOptionPane.showMessageDialog(frame, "Username changed.");
						}
					} catch (RemoteException e1) {
						e1.printStackTrace();
					}
				}
				
				else {
					JOptionPane.showMessageDialog(frame, "Username must be 4-15 characters in length, and must only contain alphanumeric characters, '.' and '_'.");
				}
								
				textFieldNewUsername.setText("");

			}
		});
		btnConfirm.setBounds(35, 82, 90, 28);
		USERNAME.add(btnConfirm);
		
		JButton button_2 = new JButton("Cancel");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textFieldNewUsername.setText("");
				USERNAME.setVisible(false);
				PASSWORD.setVisible(false);
				INFO.setVisible(false);
			}
		});
		button_2.setBounds(142, 82, 90, 28);
		USERNAME.add(button_2);
		SETTINGS.add(PASSWORD);
		PASSWORD.setLayout(null);
		
		JLabel lblCurrentPassword = new JLabel("Current Password:");
		lblCurrentPassword.setForeground(Color.WHITE);
		lblCurrentPassword.setBounds(6, 15, 115, 16);
		PASSWORD.add(lblCurrentPassword);
		
		JLabel lblNewPassword = new JLabel("New Password:");
		lblNewPassword.setHorizontalAlignment(SwingConstants.LEFT);
		lblNewPassword.setForeground(Color.WHITE);
		lblNewPassword.setBounds(6, 52, 106, 16);
		PASSWORD.add(lblNewPassword);
		
		JLabel lblRetypeNewPassword = new JLabel("Retype New:");
		lblRetypeNewPassword.setHorizontalAlignment(SwingConstants.LEFT);
		lblRetypeNewPassword.setForeground(Color.WHITE);
		lblRetypeNewPassword.setBounds(6, 89, 106, 16);
		PASSWORD.add(lblRetypeNewPassword);
		
		
		JButton button_1 = new JButton("Confirm");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					boolean formattingError = false;
					boolean matchError = false;
					
					if (oldPasswordField.getPassword().length == 0 || newPasswordField.getPassword().length == 0 || retypeNewPasswordField.getPassword().length == 0) {
						formattingError = true;
					}
					
					if (!(new String(newPasswordField.getPassword()).equals(new String(retypeNewPasswordField.getPassword())))) {
						matchError = true;
					}
					
					if (newPasswordField.getPassword().length < 6 || newPasswordField.getPassword().length > 15) {
						formattingError = true;
					}
					
					char[] temp = newPasswordField.getPassword();
					for (int i = 0; i < temp.length; i++) {
						if (!('0' <= temp[i] && temp[i] <= '9' || 'a' <= temp[i] && temp[i] <= 'z' || 'A' <= temp[i] && temp[i] <= 'Z')) {
							formattingError = true;
						}
					}
					
					if (!formattingError && !matchError) {
						if (settingsController.changePassword(new String(oldPasswordField.getPassword()), new String(newPasswordField.getPassword()))) {
							JOptionPane.showMessageDialog(frame, "Password changed.");
						}
											
						else {
							JOptionPane.showMessageDialog(frame, "Incorrect password entered.");
						}
					}
					else if (formattingError){
						JOptionPane.showMessageDialog(frame, "Passwords must be 6-15 characters long, and must only contain alphanumeric symbols.");
					}
					else {
						JOptionPane.showMessageDialog(frame, "New password and confirmation do not match.");
					}
					
					
				} catch (RemoteException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				oldPasswordField.setText(null);
				newPasswordField.setText(null);
				retypeNewPasswordField.setText(null);
				
				INFO.setVisible(false);
				PASSWORD.setVisible(false);
				USERNAME.setVisible(false);
			}
		});
		
		button_1.setBounds(36, 120, 90, 28);
		PASSWORD.add(button_1);
		
		JButton btnCancel_1 = new JButton("Cancel");
		btnCancel_1.setBounds(156, 120, 90, 28);
		PASSWORD.add(btnCancel_1);
		
		oldPasswordField = new JPasswordField();
		oldPasswordField.setBounds(117, 9, 142, 28);
		PASSWORD.add(oldPasswordField);
		
		newPasswordField = new JPasswordField();
		newPasswordField.setBounds(117, 46, 142, 28);
		PASSWORD.add(newPasswordField);
		
		retypeNewPasswordField = new JPasswordField();
		retypeNewPasswordField.setBounds(117, 83, 142, 28);
		PASSWORD.add(retypeNewPasswordField);
		
		btnCancel_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				oldPasswordField.setText(null);
				newPasswordField.setText(null);
				retypeNewPasswordField.setText(null);
				PASSWORD.setVisible(false);
				USERNAME.setVisible(false);
				INFO.setVisible(false);
			}
		});
		
		JButton btnEditPersonalInfo = new JButton("Edit Personal Info");
		btnEditPersonalInfo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				INFO.setVisible(true);
				USERNAME.setVisible(false);
				PASSWORD.setVisible(false);
			}
		});
		btnEditPersonalInfo.setBounds(231, 186, 192, 28);
		SETTINGS.add(btnEditPersonalInfo);
		
		JLabel lblFirstName_1 = new JLabel("First Name:");
		lblFirstName_1.setBounds(10, 10, 146, 16);
		lblFirstName_1.setForeground(Color.WHITE);
		INFO.add(lblFirstName_1);
		
		JLabel lblLastName_1 = new JLabel("Last Name:");
		lblLastName_1.setForeground(Color.WHITE);
		lblLastName_1.setBounds(10, 45, 146, 16);
		INFO.add(lblLastName_1);
		
		JLabel lblAge_1 = new JLabel("Age:");
		lblAge_1.setForeground(Color.WHITE);
		lblAge_1.setBounds(10, 80, 146, 16);
		INFO.add(lblAge_1);
		
		JLabel lblGender_1 = new JLabel("Gender:");
		lblGender_1.setForeground(Color.WHITE);
		lblGender_1.setBounds(10, 115, 146, 16);
		INFO.add(lblGender_1);
		
		JLabel lblLocation_1 = new JLabel("Location:");
		lblLocation_1.setForeground(Color.WHITE);
		lblLocation_1.setBounds(10, 150, 146, 16);
		INFO.add(lblLocation_1);
		
		firstNameField = new JTextField();
		firstNameField.setBounds(95, 8, 158, 20);
		INFO.add(firstNameField);
		firstNameField.setColumns(10);
		firstNameField.setText(settingsController.getUser().getUserSettings().getFirstName());
		
		lastNameField = new JTextField();
		lastNameField.setColumns(10);
		lastNameField.setBounds(95, 43, 158, 20);
		INFO.add(lastNameField);
		lastNameField.setText(settingsController.getUser().getUserSettings().getLastName());
		
		ageField = new JTextField();
		ageField.setColumns(10);
		ageField.setBounds(95, 78, 158, 20);
		INFO.add(ageField);
		ageField.setText("" + settingsController.getUser().getUserSettings().getAge());
		
		String[] gender = {"Male", "Female"};
		
		genderField = new JComboBox(gender);
		
		
		
		//genderField.setColumns(10);
		genderField.setBounds(95, 113, 158, 20);
		INFO.add(genderField);
		if (settingsController.getUser().getUserSettings().getGender().toString().equals("MALE")) {
			genderField.setSelectedIndex(0);
		}
		else {
			genderField.setSelectedIndex(1);
		}
		
		locationField = new JTextField();
		locationField.setColumns(10);
		locationField.setBounds(95, 148, 158, 20);
		INFO.add(locationField);
		locationField.setText(settingsController.getUser().getUserSettings().getLocation());
		
		JButton btnConfirmPersonalInfo = new JButton("Confirm");
		btnConfirmPersonalInfo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				boolean formattingError = false;
				boolean errorDisplayed = false;
				
				// Alphanumeric/Length test for names.
				if (firstNameField.getText().length() == 0 || firstNameField.getText().length() > 15 || lastNameField.getText().length() == 0 || lastNameField.getText().length() > 15) {
					formattingError = true;
				}
				
				String temp = firstNameField.getText();
				for (int i = 0; i < temp.length(); i++) {
					if (!('a' <= temp.charAt(i) && temp.charAt(i) <= 'z' || 'A' <= temp.charAt(i) && temp.charAt(i) <= 'Z')) {
						formattingError = true;
					}
				}
				
				temp = lastNameField.getText();
				for (int i = 0; i < temp.length(); i++) {
					if (!('a' <= temp.charAt(i) && temp.charAt(i) <= 'z' || 'A' <= temp.charAt(i) && temp.charAt(i) <= 'Z')) {
						formattingError = true;
					}
				}
				
				if (formattingError) {
					JOptionPane.showMessageDialog(frame, "First name and last name must only contain letters, and must be less than 15 characters.");
					formattingError = false;
					errorDisplayed = true;
				}
				
				// Age formatting test.
				if (ageField.getText().length() == 0 || ageField.getText().length() > 2) {
					formattingError = true;
				}
				
				temp = ageField.getText();
				for (int i = 0; i < temp.length(); i++) {
					if (!('0' <= temp.charAt(i) && temp.charAt(i) <= '9')) {
						formattingError = true;
					}
				}
				
				if (formattingError && !errorDisplayed) {
					JOptionPane.showMessageDialog(frame, "Please enter a valid age.");
					formattingError = false;
					errorDisplayed = true;
				}
								
				// Location formatting test.
				if (locationField.getText().length() == 0 || locationField.getText().length() > 15) {
					formattingError = true;
				}
				
				temp = locationField.getText();
				for (int i = 0; i < temp.length(); i++) {
					if (!('a' <= temp.charAt(i) && temp.charAt(i) <= 'z' || 'A' <= temp.charAt(i) && temp.charAt(i) <= 'Z')) {
						formattingError = true;
					}
				}
				
				if (formattingError && !errorDisplayed) {
					JOptionPane.showMessageDialog(frame, "Please enter a valid location.");
					formattingError = false;
					errorDisplayed = true;
				}
				
				if (!errorDisplayed) {
					
					String gender = (String)genderField.getSelectedItem();
					
					try {
						if (settingsController.changePersonalInfo(firstNameField.getText(), lastNameField.getText(), ageField.getText(), gender, locationField.getText()));
					} catch (RemoteException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
				}
				
				firstNameField.setText(settingsController.getUser().getUserSettings().getFirstName());
				lastNameField.setText(settingsController.getUser().getUserSettings().getLastName());
				ageField.setText("" + settingsController.getUser().getUserSettings().getAge());
				
				if (settingsController.getUser().getUserSettings().getGender().toString().equals("MALE")) {
					genderField.setSelectedIndex(0);
				}
				else {
					genderField.setSelectedIndex(1);
				}

				locationField.setText(settingsController.getUser().getUserSettings().getLocation());
				
				INFO.setVisible(false);
				PASSWORD.setVisible(false);
				USERNAME.setVisible(false);
			}
		});
		btnConfirmPersonalInfo.setBounds(33, 178, 90, 28);
		INFO.add(btnConfirmPersonalInfo);
		
		JButton btnCancel_2 = new JButton("Cancel");
		btnCancel_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				firstNameField.setText(settingsController.getUser().getUserSettings().getFirstName());
				lastNameField.setText(settingsController.getUser().getUserSettings().getLastName());
				ageField.setText("" + settingsController.getUser().getUserSettings().getAge());

				if (settingsController.getUser().getUserSettings().getGender().toString().equals("MALE")) {
					genderField.setSelectedIndex(0);
				}
				else {
					genderField.setSelectedIndex(1);
				}
				
				locationField.setText(settingsController.getUser().getUserSettings().getLocation());
				
				INFO.setVisible(false);
				PASSWORD.setVisible(false);
				USERNAME.setVisible(false);
			}
		});
		btnCancel_2.setBounds(137, 178, 90, 28);
		INFO.add(btnCancel_2);
		
		JButton btnChangeUsername = new JButton("Edit Username");
		btnChangeUsername.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				USERNAME.setVisible(true);
				PASSWORD.setVisible(false);
				INFO.setVisible(false);
				
			}
		});
		btnChangeUsername.setBounds(231, 116, 192, 28);
		SETTINGS.add(btnChangeUsername);
		
		JButton btnChangePassword = new JButton("Edit Password");
		btnChangePassword.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PASSWORD.setVisible(true);
				USERNAME.setVisible(false);
				INFO.setVisible(false);
			}
		});
		btnChangePassword.setBounds(231, 151, 192, 28);
		SETTINGS.add(btnChangePassword);
		
		JButton btnReturnToMain_1 = new JButton("Return to Main Menu");
		btnReturnToMain_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				INFO.setVisible(false);
		        PASSWORD.setVisible(false);
		        USERNAME.setVisible(false);
		        settingsController.returnToLobby();
			}
		});
		btnReturnToMain_1.setBounds(231, 451, 192, 28);
		SETTINGS.add(btnReturnToMain_1);
		
		frame.setVisible(true);
	}
}
